package com.jdy.haoduoai.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Rect;
import android.os.Looper;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Transformation;

import com.jdy.haoduoai.model.Recentlty_scores;
import com.ycsj.goldmedalnewconcept.R;

import java.util.ArrayList;

//import com.jdy.haoduoai.R;

/**
 * 柱状图
 * 
 * @author
 * 
 */
public class HistogramView extends View {

  private Paint xLinePaint;// 坐标轴 轴线 画笔：
  private Paint hLinePaint;// 坐标轴水平内部 虚线画笔
  private Paint titlePaint;// 绘制文本的画笔
  private Paint paint;// 矩形画笔 柱状图的样式信息
  /*
   * private int[] progress = { 2000, 5000, 6000, 8000, 500, 6000, 9000 };// 7
   */// 条，显示各个柱状的数据

  private int[] progress = { 10000, 2500, 5000, 3000 };

  private int[] aniProgress;// 实现动画的值
  private int[] actionProgress;// 实现动画的值
  private final int TRUE = 1;// 在柱状图上显示数字
  private int[] text;// 设置点击事件，显示哪一条柱状的信息
  private Bitmap bitmap;
  // 坐标轴左侧的数标
  private String[] ySteps;
  // 坐标轴底部的星期数
  private String[] xWeeks;
  private int flag;// 是否使用动画

  private HistogramAnimation ani;

  private int HEIGHT = dp2px(160);

  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    if (mList != null) {
      if (mList.size() <= 4) {
        setMeasuredDimension(
            (getResources().getDisplayMetrics().widthPixels - dp2px(60)),
            HEIGHT);
      } else {
        if (mList.size() % 4 > 0) {
          setMeasuredDimension((mList.size() / 4 + 1)
              * (getResources().getDisplayMetrics().widthPixels - dp2px(60)),
              HEIGHT);
        } else {
          setMeasuredDimension((mList.size() / 4)
              * (getResources().getDisplayMetrics().widthPixels - dp2px(60)),
              HEIGHT);
        }
      }

    } else {
      setMeasuredDimension(getResources().getDisplayMetrics().widthPixels
          - dp2px(60), HEIGHT);
    }

  }

  public HistogramView(Context context) {
    super(context);
    init();
  }

  public HistogramView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
  }

  ArrayList<Recentlty_scores> mList;

  @SuppressLint("WrongCall")
  public void initValues(ArrayList<Recentlty_scores> list) {
    mList = list;

    if (mList != null) {
      if (mList.size() <= 4) {
        setMeasuredDimension(
            (getResources().getDisplayMetrics().widthPixels - dp2px(60)),
            HEIGHT);
      } else {
        if (mList.size() % 4 > 0) {
          setMeasuredDimension((mList.size() / 4 + 1)
              * (getResources().getDisplayMetrics().widthPixels - dp2px(60)),
              HEIGHT);
        } else {
          setMeasuredDimension((mList.size() / 4)
              * (getResources().getDisplayMetrics().widthPixels - dp2px(60)),
              HEIGHT);
        }
      }

      aniProgress = new int[mList.size()];
      actionProgress = new int[mList.size()];
      xWeeks = new String[mList.size()];

      for (int i = 0; i < mList.size(); i++) {
        aniProgress[i] = mList.get(i).test_score;
        actionProgress[i] = mList.get(i).action_score;
        xWeeks[i] = mList.get(i).title;
      }

      invalidate();
    }
  }

  private void init() {

    ySteps = new String[] { "360", "", "180", "", "Oh" };
    xWeeks = new String[] { "", "", "", ""/* , "周五", "周六", "周日" */};
    text = new int[] { 0, 0, 0, 0, 0, 0, 0 };
    aniProgress = new int[] { 0, 0, 0, 0 /* , 0, 0, 0 */};
    actionProgress = new int[] { 100, 20, 200, 150 /* , 0, 0, 0 */};

    ani = new HistogramAnimation();
    ani.setDuration(2000);

    xLinePaint = new Paint();
    hLinePaint = new Paint();
    titlePaint = new Paint();
    paint = new Paint();

    // 给画笔设置颜色
    xLinePaint.setColor(Color.DKGRAY);
    hLinePaint.setColor(Color.LTGRAY);
    titlePaint.setColor(Color.BLACK);

    // 加载画图
    bitmap = BitmapFactory.decodeResource(getResources(),
        R.drawable.blue_round_icon);
  }

  public void start(int flag) {
    this.flag = flag;
    this.startAnimation(ani);
  }

  @SuppressLint("DrawAllocation")
  @Override
  protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    int width = getWidth();
    int height = getHeight() - dp2px(30);

    canvas.drawLine(0, height + dp2px(3), width - dp2px(30), height + dp2px(3),
        xLinePaint);

    int leftHeight = height - dp2px(5);// 左侧外周的 需要划分的高度：
    int hPerHeight = leftHeight / 4;// 分成四部分

    hLinePaint.setTextAlign(Align.CENTER);
    // 设置四条虚线
    for (int i = 0; i < 4; i++) {
      canvas.drawLine(0, dp2px(10) + i * hPerHeight, width - dp2px(30),
          dp2px(10) + i * hPerHeight, hLinePaint);
    }

    titlePaint.setTextSize(sp2px(12));
    titlePaint.setAntiAlias(true);
    titlePaint.setStyle(Paint.Style.FILL);

    // 绘制 X 周 做坐标
    int xAxisLength = width - dp2px(60);
    int columCount = xWeeks.length + 1;
    int step = xAxisLength / columCount;

    // step = (getResources().getDisplayMetrics().widthPixels - dp2px(40)) / 5;
    step = width / columCount;

    // 绘制矩形
    if (aniProgress != null && aniProgress.length > 0) {
      for (int i = 0; i < aniProgress.length; i++) {// 循环遍历将7条柱状图形画出来
        // int value = aniProgress[i];
        paint.setAntiAlias(true);// 抗锯齿效果
        paint.setStyle(Paint.Style.FILL);
        paint.setTextSize(sp2px(15));// 字体大小
        paint.setColor(Color.parseColor("#ffcd1d"));// 字体颜色
        Rect rect = new Rect();// 柱状图的形状

        if (i == 0) {
          rect.left = dp2px(30);
        } else {
          rect.left = dp2px(30) + step * (i);
        }

        rect.right = dp2px(30) + rect.left;
        canvas.drawLine((rect.left + rect.right) / 2, height + dp2px(3),
            (rect.left + rect.right) / 2, 0, hLinePaint);

        canvas.drawText(xWeeks[i], (rect.left + rect.right) / 2
            - getTextViewLength(xWeeks[i]) / 2, height + dp2px(20), titlePaint);

        rect.bottom = height + dp2px(3);
        rect.top = (int) (rect.bottom - hPerHeight * (aniProgress[i] / (90.0f)));

        canvas.drawRect(rect, paint);
        paint.setColor(Color.parseColor("#80c269"));// 字体颜色

        rect.bottom = rect.top;
        rect.top = (int) (rect.top - hPerHeight * (actionProgress[i] / (90.0f)));
        canvas.drawRect(rect, paint);
      }
    }

  }

  public float getTextViewLength(String text) {

    TextPaint textPaint = new TextPaint();
    textPaint.set(titlePaint);

    float textLength = textPaint.measureText(text);
    return textLength;
  }

  private int dp2px(int value) {
    float v = getContext().getResources().getDisplayMetrics().density;
    return (int) (v * value + 0.5f);
  }

  private int sp2px(int value) {
    float v = getContext().getResources().getDisplayMetrics().scaledDensity;
    return (int) (v * value + 0.5f);
  }

  /**
   * 设置点击事件，是否显示数字
   */
  @Override
  public boolean onTouchEvent(MotionEvent event) {
    int step = (getWidth() - dp2px(30)) / 8;
    int x = (int) event.getX();
    for (int i = 0; i < 7; i++) {
      if (x > (dp2px(15) + step * (i + 1) - dp2px(15))
          && x < (dp2px(15) + step * (i + 1) + dp2px(15))) {
        text[i] = 1;
        for (int j = 0; j < 7; j++) {
          if (i != j) {
            text[j] = 0;
          }
        }
        if (Looper.getMainLooper() == Looper.myLooper()) {
          invalidate();
        } else {
          postInvalidate();
        }
      }
    }
    return super.onTouchEvent(event);
  }

  private class HistogramAnimation extends Animation {
    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
      super.applyTransformation(interpolatedTime, t);
      if (interpolatedTime < 1.0f && flag == 2) {
        for (int i = 0; i < aniProgress.length; i++) {
          aniProgress[i] = (int) (progress[i] * interpolatedTime);
        }
      } else {
        for (int i = 0; i < aniProgress.length; i++) {
          aniProgress[i] = progress[i];
        }
      }
      invalidate();
    }
  }

}